package com.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo.model.Teacher;
import com.demo.service.TeacherService;

@Controller
public class TeacherController {

	@Autowired
	private TeacherService teacherService;

	@RequestMapping("/teacher/list.htm")
	public String list(String name, @RequestParam(value = "pageNo", required = false, defaultValue = "0") int pageNo,
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize, Model model) {
		List<Teacher> teachers = teacherService.getTeachers(name, pageNo, pageSize);
		model.addAttribute("teachers", teachers);
		model.addAttribute("name", name);
		model.addAttribute("pageNo", pageNo);
		int total = teacherService.count(name);
		int totalPageNo = total / pageSize;
		if (total % pageSize > 0) {
			totalPageNo++;
		}
		model.addAttribute("totalPageNo", totalPageNo);
		return "teacher/list";
	}

	@RequestMapping("/teacher/input.htm")
	public String input(@RequestParam(value = "id", required = false, defaultValue = "0") int id, Model model) {
		if (id > 0) {
			Teacher teacher = teacherService.getTeacherById(id);
			model.addAttribute("teacher", teacher);
		}
		return "teacher/input";
	}

	@RequestMapping("/teacher/update.htm")
	public String update(Teacher teacher) {
		teacherService.updateTeacher(teacher);
		return "redirect:/teacher/list.htm";
	}

	@RequestMapping("/teacher/delete.htm")
	public String delete(int id) {
		teacherService.deleteTeacher(id);
		return "redirect:/teacher/list.htm";
	}

}
